package com.hs.hlw.credit.system.web.util;

import com.hs.hlw.credit.system.web.exception.HlRestClientException;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by hldev on 17-11-8.
 */
public class RestfulUtil {

    public static String urlGetRequest(String url, String cookieValue) throws Exception {

        String resultStr = "";
        URL restURL = new URL(url);

        //访问的是https,则忽略ssl验证(否则需要安装)
        if ("https".equalsIgnoreCase(restURL.getProtocol())) {
            SslUtils.ignoreSsl();
        }

        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();

        try {

            //如果存在认证http头
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            if (StringUtils.isNotBlank(cookieValue)) {
                conn.setRequestProperty("Cookie", cookieValue);
            }
            conn.setAllowUserInteraction(false);

            //如果有参数
            //PrintStream ps = new PrintStream(conn.getOutputStream());
            //ps.print(query);
            //ps.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";

            while (null != (line = reader.readLine())) {
                resultStr += line;
            }
            reader.close();
        }catch (Exception ex){
            int errCode = conn.getResponseCode();
            String errMsg = conn.getResponseMessage();

            throw new HlRestClientException(ex, errCode, errMsg);
        }

        return resultStr;
    }

    public static String urlPutRequest(String urlPath, String jsonStr, String cookieValue) throws Exception {
        String result = "";
        URL url = new URL(urlPath);
        //访问的是https,则忽略ssl验证(否则需要安装)
        if ("https".equalsIgnoreCase(url.getProtocol())) {
            SslUtils.ignoreSsl();
        }

        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        try {
            urlConn.setRequestProperty("content-type", "application/json");
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setConnectTimeout(5 * 1000);
            //设置请求方式为 PUT
            urlConn.setRequestMethod("PUT");
            urlConn.setRequestProperty("Accept", "application/json");
            urlConn.setRequestProperty("Charset", "UTF-8");

            if(StringUtils.isNotBlank(cookieValue)) {
                urlConn.setRequestProperty("Cookie", cookieValue);
            }

            // 往服务器里面发送数据
            if (StringUtils.isNotBlank(jsonStr)) {
                byte[] writebytes = jsonStr.getBytes();
                // 设置文件长度
                urlConn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = urlConn.getOutputStream();
                outwritestream.write(jsonStr.getBytes());
                outwritestream.flush();
                outwritestream.close();
            }

            if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStreamReader isr = new InputStreamReader(urlConn.getInputStream());
                BufferedReader br = new BufferedReader(isr);
                String inputLine;
                while ((inputLine = br.readLine()) != null) {
                    result += inputLine;
                }
                isr.close();
                urlConn.disconnect();
            }

        } catch (Exception ex) {
            int errCode = urlConn.getResponseCode();
            String errMsg = urlConn.getResponseMessage();

            throw new HlRestClientException(ex, errCode, errMsg);
        }

        return result;

    }
}
